<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import apiMenu from '@/api/modules/menu.ts'
import apiUser from '@/api/modules/roleMange'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const loading = ref(false)
const formRef = useTemplateRef<FormInstance>('formRef')
const routes = ref<any[]>([])
const authsFlat = ref<any>([])

const form = ref({
  roleId: route.params.id as string | number ?? '',
  roleName: '',
  status: '',
  roleType: '',
  roleKey: '',
  checkedKeys: [] as string | number[],
  roleSort: 0,
  auths: [] as string[],
})
const formRules = ref<FormRules>({
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'blur' },
  ],
  roleType: [
    { required: true, message: '请选择类型', trigger: 'blur' },
  ],
  roleKey: [
    { required: true, message: '请输入角色权限', trigger: 'blur' },
  ],
  roleSort: [
    { required: true, message: '请输入角色排序', trigger: 'blur' },
  ],
})
onMounted(() => {
  getAuths()
})

// 获取路由列表
function getAuths() {
  apiMenu.list().then((res: any) => {
    routes.value = res.data
    const flat = (arr: any[]) => {
      arr.forEach((item: any) => {
        authsFlat.value.push({
          id: item.id,
          auths: item.meta.auths ? item.meta.auths : [],
        })
        if (item?.children?.length > 0) {
          flat(item.children)
        }
      })
    }
    flat(routes.value)
    if (form.value.roleId !== '') {
      getInfo()
    }
  })
}

const checkAll = computed(() => {
  const isCheckAll: {
    [key: number]: {
      checkAll: boolean
      indeterminate: boolean
    }
  } = {}

  authsFlat.value.forEach((item: any) => {
    const validAuths = item.auths || []
    let checkCount = 0
    validAuths.forEach((auth: any) => {
      if (form.value.auths.includes(auth.value)) {
        checkCount++
      }
    })
    isCheckAll[item.id] = {
      checkAll: checkCount === item.auths.length,
      indeterminate: checkCount > 0 && checkCount < item.auths.length,
    }
  })
  return isCheckAll
})
function handleCheckAll(flag: any, id: number) {
  if (flag) {
    authsFlat.value.forEach((item: any) => {
      if (item.auths && item.id === id) {
        item.auths.forEach((auth: any) => {
          if (!form.value.auths.includes(auth.value)) {
            form.value.auths.push(auth.value)
          }
        })
      }
    })
  }
  else {
    authsFlat.value.forEach((item: any) => {
      if (item.id === id) {
        item.auths.forEach((auth: any) => {
          form.value.auths = form.value.auths.filter(item => item !== auth.value)
        })
      }
    })
  }
}
// 获取角色信息
function getInfo() {
  loading.value = true
  apiUser.detail(form.value.roleId).then((res: any) => {
    loading.value = false
    form.value.roleName = res.data.roleName
    form.value.status = res.data.status
    form.value.roleType = res.data.roleType
    form.value.checkedKeys = res.data.checkedKeys
    form.value.auths = res.data.auths || []
    form.value.roleSort = res.data.roleSort
    form.value.roleKey = res.data.roleKey
  })
}

// 提交表单
function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        if (form.value.roleId === '') {
          apiUser.create(form.value).then((res: any) => {
            if (res.code === 200) {
              ElMessage.success({
                message: '新增成功',
              })
              goBack()
            }
          })
        }
        else {
          form.value.roleId = Number(form.value.roleId)
          apiUser.edit(form.value).then((res: any) => {
            if (res.code === 200) {
              ElMessage.success({
                message: '编辑成功',
              })
              goBack()
            }
          })
        }
      }
    })
  })
}
function onCancel() {
  goBack()
}
// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'roleManagementList' })
  }
  else {
    router.push({ name: 'roleManagementList' })
  }
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'roleManagementCreate' ? '新增角色' : '编辑角色信息'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="120px" label-suffix="：">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <div class="formContent">
          <ElFormItem label="角色名称" prop="roleName">
            <ElInput v-model="form.roleName" placeholder="请输入角色名称" />
          </ElFormItem>
          <ElFormItem label="角色权限" prop="roleKey">
            <ElInput v-model="form.roleKey" placeholder="请输入角色名称" />
          </ElFormItem>
          <ElFormItem label="角色排序" prop="roleSort">
            <ElInput v-model="form.roleSort" placeholder="请输入角色名称" />
          </ElFormItem>
          <ElFormItem label="角色状态" prop="status">
            <ElSwitch v-model="form.status" inline-prompt active-text="启用" inactive-text="停用" active-value="0" inactive-value="1" />
          </ElFormItem>
          <ElFormItem label="角色类型" prop="roleType">
            <ElRadioGroup v-model="form.roleType">
              <ElRadioButton value="0">
                普通
              </ElRadioButton>
              <ElRadioButton value="1">
                管理员
              </ElRadioButton>
              <ElRadioButton value="2">
                超管
              </ElRadioButton>
            </ElRadioGroup>
          </ElFormItem>
          <ElTable :data="routes" row-key="id" stripe highlight-current-row default-expand-all border :style="{ lineHeight: 'normal' }">
            <ElTableColumn width="300" label="模块">
              <template #default="{ row }">
                {{ row.meta.title }}
              </template>
            </ElTableColumn>
            <ElTableColumn label="权限">
              <template #default="{ row }">
                <ElCheckbox v-if="row.meta.auths?.length" v-model="checkAll[row.id].checkAll" :indeterminate="checkAll[row.id].indeterminate" @change="handleCheckAll($event, row.id)">
                  全选
                </ElCheckbox>
                <ElCheckboxGroup v-model="form.auths">
                  <ElCheckbox v-for="auth in row.meta.auths" :key="auth.value" :value="auth.value">
                    {{ auth.name }}
                  </ElCheckbox>
                </ElCheckboxGroup>
              </template>
            </ElTableColumn>
          </ElTable>
          <FaFixedActionBar>
            <ElButton type="primary" size="large" @click="onSubmit">
              提交
            </ElButton>
            <ElButton size="large" @click="onCancel">
              取消
            </ElButton>
          </FaFixedActionBar>
        </div>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.el-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
.label-tip {
  display: inline-flex;
  margin-left: 10px;
  color: var(--el-text-color-disabled);
}
</style>
